package com.ruoyi.business.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.business.Util.IdUtil;
import com.ruoyi.business.domain.*;
import com.ruoyi.business.mapper.TeacherManageMapper;
import com.ruoyi.business.service.*;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.exception.MyException;
import com.ruoyi.system.domain.MySysRole;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserRoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.*;
import java.util.stream.Collectors;


@Service
public class TeacherManageImpl extends ServiceImpl<TeacherManageMapper, TeacherManage> implements ITeacherManageService {
    @Autowired
    private IUserPostService iUserPostService;

    @Autowired
    private IBusGradeService iBusGradeService;

    @Autowired
    private IBusGradeTeacherService ibusGradeTeacherService;

    @Autowired
    private IBusSubjectService iBusSubjectService;

    @Autowired
    private ISysRoleService iSysRoleService;

    @Autowired
    private ISysUserRoleService iSysUserRoleService;

    @Autowired
    private IBusStudentParentsService iBusStudentParentsService;

    @Autowired
    private  TeacherManageMapper teacherMapper;
    /**
     * 查询所有的教师，为分页
     * @return 所有的教师
     */
    @Override
    public List<TeacherManage> allTeacherManages() {
        //拿取所有教师的信息
        List<Long> teacherManageIds = this.getTeacherManageInfo();

        //结果集
        List<TeacherManage> result = new ArrayList<>();

        if (teacherManageIds.size()>0){
            LambdaQueryWrapper<TeacherManage> teacherManageLambdaQueryWrapper = new LambdaQueryWrapper<>();
            teacherManageLambdaQueryWrapper.in(TeacherManage::getUserId,teacherManageIds);
            List<TeacherManage> list = this.list(teacherManageLambdaQueryWrapper);
            result = this.auto(list);
        }

        //历遍封装返回
        return result;
    }

    /**
     * 条件查询
     */
    @Override
    public List<TeacherManage> conditionTeacherManages(String name, Integer sex, Integer ys) {
        List<Long> teacherManageIds = this.getTeacherManageInfo();
        //拿到所有教师的ID
        LambdaQueryWrapper<TeacherManage> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(TeacherManage::getUserId,teacherManageIds);
        lambdaQueryWrapper.like(!name.isEmpty(),TeacherManage::getNickName,name);
        lambdaQueryWrapper.eq(sex != null,TeacherManage::getSex,sex);
        List<TeacherManage> list = this.list(lambdaQueryWrapper);
        //封装所带班级及课程信息
        List<TeacherManage> teacherManages = this.auto(list);
        //最后教师的结果集
        List<TeacherManage> teacherManageList = new ArrayList<>();
        //班主任集
        List<TeacherManage> headTeacherList = new ArrayList<>();
        //教师分类---班主任或者非班主任
        for (TeacherManage teacher: teacherManages) {
            if (ys == 1 && teacher.getHeadTeacher().equals("1")){
                headTeacherList.add(teacher);
            } else {
                teacherManageList.add(teacher);
            }
        }
        if (ys == 1){
            return headTeacherList;
        }else {
            return teacherManageList;
        }

    }




    /**
     * 一个name的查询条件
     * @param name
     * @return
     */
    @Override
    public List<TeacherManage> conditionTeacherManages1(String name) {

        //所有教师的ID集
        List<Long> teacherManageIds = this.getTeacherManageInfo();
        //如果集合不是空的
        if(!teacherManageIds.isEmpty()){
            //拿到符合条件的教师的信息集
            LambdaQueryWrapper<TeacherManage> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.in(TeacherManage::getUserId,teacherManageIds);
            lambdaQueryWrapper.like(!name.isEmpty(),TeacherManage::getNickName,name);
            List<TeacherManage> teacherManages = this.list(lambdaQueryWrapper);
            //如果没有符合条件的教师,也需要做出判定
            if (teacherManages.isEmpty()){
                //返回个空值
                return new ArrayList<>();
            }else {
                //封装所带班级及课程信息
                return this.auto(teacherManages);
            }
        }
        return new ArrayList<>();
    }




    /**
     * 新增教师
     * @param pointOnwTeacherManageInfo 新增教师Dto
     * @return 布尔型
     */
    @Override
    public boolean addTeacherManageInfo(PointOnwTeacherManageInfo pointOnwTeacherManageInfo) {
        //用来判断整个增加的所以逻辑是否都写入
        boolean save1 = false;
        boolean save2 = false;
        boolean save3 = false;
        boolean save4 = false;
        boolean save5;
        boolean update = false;
        //用来做判断班主任
        boolean checkHeadTeacher =false;

        //-----------用户的判断----------------
        TeacherManage teacherManage = new TeacherManage();
        BeanUtils.copyProperties(pointOnwTeacherManageInfo,teacherManage);
        //如果这个传入的用户信息，其手机号，是设置为账号信息，但是这个账号可能已经是一个家长
        LambdaQueryWrapper<TeacherManage> userCheckTeacherManage = new LambdaQueryWrapper<>();
        userCheckTeacherManage.eq(TeacherManage::getUserName,teacherManage.getPhonenumber());
        TeacherManage checkTeacherManage = getOne(userCheckTeacherManage);
        //如果这个人的账号不存在
        boolean save;
        if (checkTeacherManage == null){
            //用户表的添加
            //初始密码
            teacherManage.setPassword("123456");
            teacherManage.setDeptId(200L);
            //新建用户ID
            Long userId = Long.valueOf(IdWorker.getIdStr().substring(0, 16));
            teacherManage.setUserId(userId);
            teacherManage.setUserName(teacherManage.getPhonenumber());
            //先往用户表中写入这个老师的信息
            save = this.save(teacherManage);
            //否则就是做一个赋值的操作
        }else {
            teacherManage=checkTeacherManage;
            save = true;
        }
        //开始pointOnwTeacherManageInfo---->TeacherManage

        Long userId = teacherManage.getUserId();
        //拿到这个科目对应授课班级
        Map<String, List<Long>> mapSubject = new HashMap<>();
        //用来封装如果是班主任的所带班级
        List<Long> bringGradeId = new ArrayList<>();

        //既然这里是对于课程的封装，那么为了方便不改动代码，我们可以直接给它传入的字段进行切割，然后造一个map出来

        //拿到授课信息
        List<String> teachingInfo = pointOnwTeacherManageInfo.getTeachingInfo();
        for (String Info : teachingInfo) {
            String[] split = Info.split(":");
            //班主任:科目:班级Id、任课老师:科目:班级Id
            //切割出来应该有三个值0 1 2  只需要1  2 的课程以及班级
            //科目名称
            String subjectName = split[1];
            //班级Id
            Long gradeId = Long.valueOf(split[2]);
            //用来判断是否为班主任的信息
            if (split[0].equals("班主任")){
                bringGradeId.add(gradeId);
                checkHeadTeacher = true;
            }

            //当这个课程的key未被存入
            if (!mapSubject.containsKey(subjectName)){
                List<Long> gradeIds = new ArrayList<>();
                gradeIds.add(gradeId);
                mapSubject.put(subjectName,gradeIds);
                //当这个课程的key已经被存入
            }else if (mapSubject.containsKey(subjectName)){
                //如果已经有这个key了就直接往其value中添加一个新的班级Id
                mapSubject.get(subjectName).add(gradeId);
            }
        }
        //修改接口没有传班主任标识
       if (teacherManage.getHeadTeacher() == null){
           if (checkHeadTeacher){
               teacherManage.setHeadTeacher("1");
           }else {
               teacherManage.setHeadTeacher("0");
           }
       }

        //向userPost、userRole表中写入相关的数据---这里是针对班主任的写入--------特殊
        if (teacherManage.getHeadTeacher().equals("1") ){
            //userPost
            UserPost userPost = new UserPost();
            userPost.setUserId(userId);
            userPost.setPostId(1L);
            save1 = iUserPostService.save(userPost);
            //userRole
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(100L);
            sysUserRole.setUserId(userId);
            save4 = iSysUserRoleService.save(sysUserRole);
            for (Long gradeId : bringGradeId) {
                LambdaQueryWrapper<BusGrade> busGradeWrapper = new LambdaQueryWrapper<>();
                busGradeWrapper.eq(BusGrade::getGradeId,gradeId);
                BusGrade busGrade = iBusGradeService.getOne(busGradeWrapper);
                busGrade.setUserId(teacherManage.getUserId());
                //修改其班主任的信息
                 update = iBusGradeService.update(busGrade, busGradeWrapper);
            }
        }


        //向UserRole中写入数据
        //userRole任课教师标识
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setRoleId(101L);
        sysUserRole.setUserId(userId);
        save5 = iSysUserRoleService.save(sysUserRole);


        //拿到课程mapKey
        Set<String> keySet = mapSubject.keySet();
        for (String key:keySet) {
            //拿到课程所对应的这个班级集
            List<Long> gradeIdList = mapSubject.get(key);
            //查询到这个课程所对应的subject对象
            LambdaQueryWrapper<BusSubject> subjectLambdaQueryWrapper = new LambdaQueryWrapper<>();
            subjectLambdaQueryWrapper.eq(BusSubject::getSubjectName,key);
            BusSubject subject = iBusSubjectService.getOne(subjectLambdaQueryWrapper);
            //subject+1等同于postID,其它课程
            Long subjectId = subject.getSubjectId();

            //普通情况下这个教师对应的职业就是其课程ID+1=PostId-------普通老师
            UserPost userPost = new UserPost();
            userPost.setUserId(userId);
            userPost.setPostId(subjectId+1);
            save2 = iUserPostService.save(userPost);

            //向grade—teacher表中写入相关的数据
            for (Long gradeId: gradeIdList) {
                BusGradeTeacher busGradeTeacher = new BusGradeTeacher();
                busGradeTeacher.setGradeId(gradeId);
                //postID 1 是班主任  课程id+1是对应职业
                busGradeTeacher.setPostId(subjectId+1);
                busGradeTeacher.setUserId(userId);
                busGradeTeacher.setSubjectId(subjectId);
                save3 = ibusGradeTeacherService.save(busGradeTeacher);
            }
        }

        //最后审核对象的结果是否都为true
        boolean result;
        //需要判断是否为班主任
        if (teacherManage.getHeadTeacher().equals("1")){
            result = save && save1 && save2 && save3 && update && save4;
        }else {
            result = save  && save2 && save3 && save5;
        }
        return result ;
    }

    /**
     * 新增教师测试
     * @param pointOnwTeacherManageInfo 新增教师Dto
     * @return 布尔型
     */
    @Transactional
    @Override
    public AjaxResult addTeacherManageInfoTest(PointOnwTeacherManageInfo pointOnwTeacherManageInfo){
        //教师涉及到的表
        //用户表、角色表、Post表、busGrade、busTeacherGrade
        //用户表中的数据肯定是唯一的，修改其中的信息即可
        //用户ID
        Long userId = IdUtil.getId();
        //nickName名字
        String nickName = pointOnwTeacherManageInfo.getNickName();
        //性别
        String sex = pointOnwTeacherManageInfo.getSex();
        //手机号
        String phoneNumber = pointOnwTeacherManageInfo.getPhonenumber();
        //密码
        String password = pointOnwTeacherManageInfo.getPassword();

        //通过手机号来判断这个新增人的手机号信息是否以及存在---有可能是家长的身份已经存在
        LambdaQueryWrapper<TeacherManage> teacherManageLambdaQueryWrapper = new LambdaQueryWrapper<>();
        teacherManageLambdaQueryWrapper.eq(TeacherManage::getUserName,phoneNumber);
        //如果不为空  则证明这个人已经存在系统
        TeacherManage checkTeacherManage = this.getOne(teacherManageLambdaQueryWrapper);
        //此时新增的教师应该是，不是空的就修改，是空的就新增
        if (checkTeacherManage == null){
          TeacherManage teacherManage = new TeacherManage();
            //新增的数据
            teacherManage.setUserId(userId);
            teacherManage.setNickName(nickName);
            teacherManage.setSex(sex);
            teacherManage.setPhonenumber(phoneNumber);
            teacherManage.setUserName(phoneNumber);
            teacherManage.setDeptId(200L);
            teacherManage.setPassword(SecurityUtils.encryptPassword(password));
            //将新增的用户存入用户表
            this.save(teacherManage);
        }else {
            userId = checkTeacherManage.getUserId();
            //拿这个用户的原数据
            LambdaQueryWrapper<TeacherManage> teacherManageWrapper = new LambdaQueryWrapper<>();
            teacherManageWrapper.eq(TeacherManage::getUserId,userId);
            //新增的数据
            checkTeacherManage.setNickName(nickName);
            checkTeacherManage.setSex(sex);
            checkTeacherManage.setPhonenumber(phoneNumber);
            checkTeacherManage.setUserName(phoneNumber);
            checkTeacherManage.setDeptId(200L);
            checkTeacherManage.setPassword(SecurityUtils.encryptPassword(password));
            //先保存用户表
            this.update(checkTeacherManage,teacherManageWrapper);
        }


        List<String> teachingInfo = pointOnwTeacherManageInfo.getTeachingInfo();

        //判断班主任Flag，仅为了做一次班主任的Post  Role的添加
        boolean flagBzr = false;

        for (String Info : teachingInfo) {
            /*
             "班主任:语文:201601"
             "任课教师:数学:201601"
             */
            String[] key = Info.split(":");
            //任职
            String major = key[0];
            //课程
            String subjectName = key[1];
            //班级
            String gradeId = key[2];
            //首先对于Role，Post表进行处理
            //Role ----分为是否为班主任
            if (major.equals("班主任") ){
                //处理班主任Role信息
                if (!flagBzr){
                    flagBzr = true;
                    //Role  班主任
                    LambdaQueryWrapper<SysUserRole> sysUserRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    sysUserRoleLambdaQueryWrapper.eq(SysUserRole::getUserId,userId);
                    sysUserRoleLambdaQueryWrapper.eq(SysUserRole::getRoleId,100L);
                    SysUserRole userRole = iSysUserRoleService.getOne(sysUserRoleLambdaQueryWrapper);
                    //如果这条班主任角色Id不在就添加进去
                    if (userRole == null){
                        SysUserRole sysUserRole = new SysUserRole();
                        sysUserRole.setRoleId(100L);
                        sysUserRole.setUserId(userId);
                        iSysUserRoleService.save(sysUserRole);
                    }
                    //在Post表中增添一条班主任的信息
                    UserPost addUserPost = new UserPost();
                    addUserPost.setUserId(userId);
                    addUserPost.setPostId(1L);
                    iUserPostService.save(addUserPost);
                    //向teacherGrade添加一条班主任的空课程
                    BusGradeTeacher busGradeHeadTeacher = new BusGradeTeacher();
                    busGradeHeadTeacher.setGradeId(Long.valueOf(gradeId));
                    busGradeHeadTeacher.setPostId(1L);
                    busGradeHeadTeacher.setUserId(userId);

                    //为了避免一个人多条数据，先再班级授课信息表中，先查询一遍
                    LambdaQueryWrapper<BusGradeTeacher> busGradeHeadWrapper = new LambdaQueryWrapper<>();
                    busGradeHeadWrapper.eq(BusGradeTeacher::getGradeId,busGradeHeadTeacher.getGradeId());
                    busGradeHeadWrapper.eq(BusGradeTeacher::getPostId,busGradeHeadTeacher.getPostId());
                    busGradeHeadWrapper.eq(BusGradeTeacher::getUserId,busGradeHeadTeacher.getUserId());
                    busGradeHeadWrapper.eq(BusGradeTeacher::getSubjectId,busGradeHeadTeacher.getSubjectId());
                    BusGradeTeacher gradeTeacherInfo = ibusGradeTeacherService.getOne(busGradeHeadWrapper);
                    if (gradeTeacherInfo == null){
                        ibusGradeTeacherService.save(busGradeHeadTeacher);
                    }
                }

                //busGrade班级班主任任职
                LambdaQueryWrapper<BusGrade> busGradeLambdaQueryWrapper =new LambdaQueryWrapper<>();
                busGradeLambdaQueryWrapper.eq(BusGrade::getGradeId,gradeId);
                BusGrade busGrade = iBusGradeService.getOne(busGradeLambdaQueryWrapper);
                //班级不存在的判断
                if (busGrade == null) return AjaxResult.error("不存在该班级："+gradeId);
                //班主任Id 不相等就执行修改  可能还是同班的情况
                if ( busGrade.getUserId() ==null || !busGrade.getUserId().equals(userId)){
                    busGrade.setUserId(userId);
                    iBusGradeService.update(busGrade,busGradeLambdaQueryWrapper);
                }
            }else {
                //如果是任课老师
                LambdaQueryWrapper<SysUserRole> sysUserRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
                sysUserRoleLambdaQueryWrapper.eq(SysUserRole::getUserId,userId);
                sysUserRoleLambdaQueryWrapper.eq(SysUserRole::getRoleId,101L);
                SysUserRole userRole = iSysUserRoleService.getOne(sysUserRoleLambdaQueryWrapper);
                //如果这条教师角色Id不在就添加进去
                if (userRole == null){
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setRoleId(101L);
                    sysUserRole.setUserId(userId);
                    iSysUserRoleService.save(sysUserRole);
                }
            }



            //POST加课程的处理  以及busGradeTeacher表中信息修改
            //对于UserPost 表中的数据
            //拿到这个课程Id
            LambdaQueryWrapper<BusSubject> subjectLambdaQueryWrapper = new LambdaQueryWrapper<>();
            subjectLambdaQueryWrapper.eq(BusSubject::getSubjectName,subjectName);
            BusSubject busSubject = iBusSubjectService.getOne(subjectLambdaQueryWrapper);
            //该课程Id
            Long subjectId = busSubject.getSubjectId();

            BusGradeTeacher busGradeTeacher = new BusGradeTeacher();
            busGradeTeacher.setPostId(subjectId+1);
            busGradeTeacher.setGradeId(Long.valueOf(gradeId));
            busGradeTeacher.setSubjectId(subjectId);
            busGradeTeacher.setUserId(userId);
            //存储该条教学信息
            try {
                ibusGradeTeacherService.save(busGradeTeacher);
            }catch (Exception e){
                throw new MyException("任课岗位存在冲突"+"("+pointOnwTeacherManageInfo.getNickName()+busGradeTeacher.getGradeId()+subjectName+")");
            }
            //向Post增加信息
            LambdaQueryWrapper<UserPost> userPostLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userPostLambdaQueryWrapper.eq(UserPost::getUserId,userId);
            userPostLambdaQueryWrapper.eq(UserPost::getPostId,subjectId+1);
            //用来判断是否有这个人的user_post信息
            UserPost userPost = iUserPostService.getOne(userPostLambdaQueryWrapper);
            //这个对应的信息不存在才进行存储
            if (userPost != null){
                UserPost userPostBySubject = new UserPost();
                userPostBySubject.setUserId(userId);
                userPostBySubject.setPostId(subjectId+1);
                iUserPostService.save(userPostBySubject);
            }
        }

        //同时还会发生一种情况就是，他被撤销了班主任的任职，需要删除Role表中的班主任信息
        if (!flagBzr){
            //依然为false，那么就得删除其Role 表中班主任的信息
            LambdaQueryWrapper<SysUserRole> sysUserRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
            sysUserRoleLambdaQueryWrapper.eq(SysUserRole::getUserId,userId);
            sysUserRoleLambdaQueryWrapper.eq(SysUserRole::getRoleId,100L);
            SysUserRole sysUserRole = iSysUserRoleService.getOne(sysUserRoleLambdaQueryWrapper);
            //也就是说前面是任职过班主任的，但是现在不任职了，就得删除
            if (sysUserRole != null){
                iSysUserRoleService.remove(sysUserRoleLambdaQueryWrapper);
            }
        }
        return AjaxResult.success();
    }

    //修改教师信息
    @Transactional
    @Override
    public AjaxResult updateTeacherManageInfo(PointOnwTeacherManageInfo pointOnwTeacherManageInfo){
            //教师涉及到的表
            //用户表、角色表、Post表、busGrade、busTeacherGrade
            //用户表中的数据肯定是唯一的，修改其中的信息即可
            //用户ID
            Long userId = pointOnwTeacherManageInfo.getUserId();
            //nickName名字
            String nickName = pointOnwTeacherManageInfo.getNickName();
            //性别
            String sex = pointOnwTeacherManageInfo.getSex();
            //手机号
            String phoneNumber = pointOnwTeacherManageInfo.getPhonenumber();

            //通过手机号来判断这个修改人的手机号信息是否以及存在
            LambdaQueryWrapper<TeacherManage> teacherManageLambdaQueryWrapper = new LambdaQueryWrapper<>();
            teacherManageLambdaQueryWrapper.eq(TeacherManage::getUserName, phoneNumber);
            //并且不是这个本用户
            teacherManageLambdaQueryWrapper.ne(TeacherManage::getUserId, userId);
            TeacherManage checkTeacherManage = this.getOne(teacherManageLambdaQueryWrapper);
            if (checkTeacherManage == null) {
                //拿这个用户的原数据
                LambdaQueryWrapper<TeacherManage> teacherManageWrapper = new LambdaQueryWrapper<>();
                teacherManageWrapper.eq(TeacherManage::getUserId, userId);
                TeacherManage teacherManage = this.getOne(teacherManageWrapper);
                //再将可能被修改的数据重新添加进来
                teacherManage.setNickName(nickName);
                teacherManage.setSex(sex);
                teacherManage.setPhonenumber(phoneNumber);
                //手机号修改了  同时账号也要被修改
                teacherManage.setUserName(phoneNumber);

                //先保存用户表
                this.update(teacherManage, teacherManageWrapper);
            } else {
                //手机号已经存在  重复，有误
                return AjaxResult.error("手机号存在");
            }


            //清空该用户postId---连同班主任信息一起删除
            LambdaQueryWrapper<UserPost> userPostWrapper = new LambdaQueryWrapper<>();
            userPostWrapper.eq(UserPost::getUserId, userId);
            iUserPostService.remove(userPostWrapper);

            //清空该用户的busGradeTeacher
            LambdaQueryWrapper<BusGradeTeacher> busGradeTeacherLambdaQueryWrapper = new LambdaQueryWrapper<>();
            busGradeTeacherLambdaQueryWrapper.eq(BusGradeTeacher::getUserId, userId);
            ibusGradeTeacherService.remove(busGradeTeacherLambdaQueryWrapper);

            //清空这个人在busGrade中可能任职班主任，全部清空-如果修改中有所涉及班主任再重新设置
            LambdaQueryWrapper<BusGrade> busGradeDeleteWrapper = new LambdaQueryWrapper<>();
            busGradeDeleteWrapper.eq(BusGrade::getUserId, userId);
            List<BusGrade> busGradeTeacherHeadList = iBusGradeService.list(busGradeDeleteWrapper);
            if (!busGradeTeacherHeadList.isEmpty()) {
                for (BusGrade busGrade : busGradeTeacherHeadList) {
                    busGrade.setUserId(null);
                    iBusGradeService.myUpdateBusGrade(busGrade);
                }
            }

            //课程的修改
            List<String> teachingInfo = pointOnwTeacherManageInfo.getTeachingInfo();

            //判断班主任Flag，仅为了做一次班主任的Post  Role的添加
            boolean flagBzr = false;

            for (String Info : teachingInfo) {
            /*
             "班主任:语文:201601"
             "任课教师:数学:201601"
             */
                String[] key = Info.split(":");
                //任职
                String major = key[0];
                //课程
                String subjectName = key[1];
                //班级
                String gradeId = key[2];
                //首先对于Role，Post表进行处理
                //Role ----分为是否为班主任
                if (major.equals("班主任")) {
                    //处理班主任Role信息
                    if (!flagBzr) {
                        flagBzr = true;
                        //Role  班主任
                        LambdaQueryWrapper<SysUserRole> sysUserRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
                        sysUserRoleLambdaQueryWrapper.eq(SysUserRole::getUserId, userId);
                        sysUserRoleLambdaQueryWrapper.eq(SysUserRole::getRoleId, 100L);
                        SysUserRole userRole = iSysUserRoleService.getOne(sysUserRoleLambdaQueryWrapper);
                        //如果这条班主任角色Id不在就添加进去
                        if (userRole == null) {
                            SysUserRole sysUserRole = new SysUserRole();
                            sysUserRole.setRoleId(100L);
                            sysUserRole.setUserId(userId);
                            iSysUserRoleService.save(sysUserRole);
                        }
                        //在Post表中增添一条班主任的信息
                        UserPost addUserPost = new UserPost();
                        addUserPost.setUserId(userId);
                        addUserPost.setPostId(1L);
                        iUserPostService.save(addUserPost);
                    }


                    //busGrade班级班主任任职
                    LambdaQueryWrapper<BusGrade> busGradeLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    busGradeLambdaQueryWrapper.eq(BusGrade::getGradeId, gradeId);
                    BusGrade busGrade = iBusGradeService.getOne(busGradeLambdaQueryWrapper);
                    //班主任Id 不相等就执行修改  可能还是同班的情况
                    if (busGrade.getUserId() == null || !busGrade.getUserId().equals(userId)) {
                        busGrade.setUserId(userId);
                        iBusGradeService.update(busGrade, busGradeLambdaQueryWrapper);
                    }
                } else {
                    //如果是任课老师
                    LambdaQueryWrapper<SysUserRole> sysUserRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    sysUserRoleLambdaQueryWrapper.eq(SysUserRole::getUserId, userId);
                    sysUserRoleLambdaQueryWrapper.eq(SysUserRole::getRoleId, 101L);
                    SysUserRole userRole = iSysUserRoleService.getOne(sysUserRoleLambdaQueryWrapper);
                    //如果这条教师角色Id不在就添加进去
                    if (userRole == null) {
                        SysUserRole sysUserRole = new SysUserRole();
                        sysUserRole.setRoleId(101L);
                        sysUserRole.setUserId(userId);
                        iSysUserRoleService.save(sysUserRole);
                    }
                }


                //POST加课程的处理  以及busGradeTeacher表中信息修改
                //对于UserPost 表中的数据
                //拿到这个课程Id
                LambdaQueryWrapper<BusSubject> subjectLambdaQueryWrapper = new LambdaQueryWrapper<>();
                subjectLambdaQueryWrapper.eq(BusSubject::getSubjectName, subjectName);
                BusSubject busSubject = iBusSubjectService.getOne(subjectLambdaQueryWrapper);
                //该课程Id
                Long subjectId = busSubject.getSubjectId();

                BusGradeTeacher busGradeTeacher = new BusGradeTeacher();
                busGradeTeacher.setPostId(subjectId + 1);
                busGradeTeacher.setGradeId(Long.valueOf(gradeId));
                busGradeTeacher.setSubjectId(subjectId);
                busGradeTeacher.setUserId(userId);
                //存储该条教学信息
                try {
                    ibusGradeTeacherService.save(busGradeTeacher);
                }catch (Exception e){
                    throw new MyException("岗位存在冲突");
                }
                //存储其Post信息
                LambdaQueryWrapper<UserPost> userPostLambdaQueryWrapper = new LambdaQueryWrapper<>();
                userPostLambdaQueryWrapper.eq(UserPost::getUserId, userId);
                userPostLambdaQueryWrapper.eq(UserPost::getPostId, subjectId + 1);
                if (iUserPostService.getOne(userPostLambdaQueryWrapper) == null) {
                    //向Post增加信息
                    UserPost userPostBySubject = new UserPost();
                    userPostBySubject.setUserId(userId);
                    userPostBySubject.setPostId(subjectId + 1);
                    iUserPostService.save(userPostBySubject);
                }
            }

            //同时还会发生一种情况就是，他被撤销了班主任的任职，需要删除Role表中的班主任信息，
            if (!flagBzr) {
                //依然为false，那么就得删除其Role 表中班主任的信息
                LambdaQueryWrapper<SysUserRole> sysUserRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
                sysUserRoleLambdaQueryWrapper.eq(SysUserRole::getUserId, userId);
                sysUserRoleLambdaQueryWrapper.eq(SysUserRole::getRoleId, 100L);
                SysUserRole sysUserRole = iSysUserRoleService.getOne(sysUserRoleLambdaQueryWrapper);
                //也就是说前面是任职过班主任的，但是现在不任职了，就得删除
                if (sysUserRole != null) {
                    iSysUserRoleService.remove(sysUserRoleLambdaQueryWrapper);
                }
            }
        return AjaxResult.success();
    }


    //编辑教师-回显数据
    @Override
    public PointOnwTeacherManageInfo echoTeacherManageInfo(Long UserId) {
        LambdaQueryWrapper<TeacherManage> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(TeacherManage::getUserId,UserId);
        TeacherManage teacherManage = this.getOne(lambdaQueryWrapper);
        PointOnwTeacherManageInfo pointOnwTeacherManageInfo = new PointOnwTeacherManageInfo();
        BeanUtils.copyProperties(teacherManage, pointOnwTeacherManageInfo);
        return this.echoTest(pointOnwTeacherManageInfo);
    }


    //删除教师
    @Override
    public boolean deleteTeacherManageInfo(Long UserId) throws DataAccessException {

        LambdaQueryWrapper<BusStudentParents> busStudentParentsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        busStudentParentsLambdaQueryWrapper.eq(BusStudentParents::getUserId,UserId);
        //用来判断父母用户的存在与否
        boolean parentsEmpty = iBusStudentParentsService.list(busStudentParentsLambdaQueryWrapper).isEmpty();
        //删除Post表中的数据
        LambdaQueryWrapper<UserPost> userPostWrapper = new LambdaQueryWrapper<>();
        userPostWrapper.eq(UserPost::getUserId,UserId);
        //删除userPost表信息
        boolean remove = iUserPostService.remove(userPostWrapper);
        //如果这个用户不是家长就还要删除用户表信息
        if(parentsEmpty){
            //删除用户表信息
            LambdaQueryWrapper<TeacherManage> sysUserWrapper = new LambdaQueryWrapper<>();
            sysUserWrapper.eq(TeacherManage::getUserId,UserId);
            this.remove(sysUserWrapper);

        }

        //删除角色表信息
        LambdaQueryWrapper<SysUserRole> sysUserRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //删除其不等于家长的数据-----这个不影响它到底是不是有存在多重身份
        sysUserRoleLambdaQueryWrapper.eq(SysUserRole::getUserId,UserId);
        sysUserRoleLambdaQueryWrapper.last("and (role_id = 100 or role_id = 101) ");
        iSysUserRoleService.remove(sysUserRoleLambdaQueryWrapper);

        //删除gradeTeacher表信息
        LambdaQueryWrapper<BusGradeTeacher> gradeTeacherWrapper = new LambdaQueryWrapper<>();
        gradeTeacherWrapper.eq(BusGradeTeacher::getUserId,UserId);
        boolean remove2;
        try {
            remove2 = ibusGradeTeacherService.remove(gradeTeacherWrapper);

        }catch (Exception e){
            throw new MyException("该教师还存在任课,无法删除");
        }

        //删除其班主任的信息
        LambdaQueryWrapper<BusGrade> busGradeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        busGradeLambdaQueryWrapper.eq(BusGrade::getUserId,UserId);
        List<BusGrade> list = iBusGradeService.list(busGradeLambdaQueryWrapper);
        if (!list.isEmpty()){
            for (BusGrade busGrade : list) {
                //将其班主任Id设置为空
                busGrade.setUserId(null);
                iBusGradeService.myUpdateBusGrade(busGrade);
            }
        }
        return remove2 && remove;
    }

    //导出方法
    @Override
    public List<TeacherManageExport> exportGradeTeacherInfo() {
        List<TeacherManage> teacherManages = this.allTeacherManages();
        List<TeacherManageExport> teacherManageExports = new ArrayList<>();
        if (!teacherManages.isEmpty()){
            for (TeacherManage teacherManage : teacherManages) {
                //按其课程，班级来拆分
                Map<String, List<Long>> mapSubject = teacherManage.getMapSubject();
                Set<String> subjectKeySet = mapSubject.keySet();
                if (!subjectKeySet.isEmpty()){
                    for (String subject : subjectKeySet) {
                        //
                        TeacherManageExport teacherManageExport = new TeacherManageExport();
                        teacherManageExport.setNickName(teacherManage.getNickName());
                        teacherManageExport.setPhonenumber(teacherManage.getPhonenumber());
                        teacherManageExport.setSex(teacherManage.getSex());
                        //集合去括号
                        String bringClasses = StringUtils.strip(teacherManage.getGradeNameList().toString(), "[]");
                        teacherManageExport.setBringClass(bringClasses);
                        teacherManageExport.setSubjectName(subject);
                        //拿到这个授课班级的集合
                        String teachingClasses = StringUtils.strip(mapSubject.get(subject).toString(), "[]");
                        teacherManageExport.setClasses(teachingClasses);
                        teacherManageExports.add(teacherManageExport);
                    }
                }else {
                    TeacherManageExport teacherManageExport = new TeacherManageExport();
                    teacherManageExport.setNickName(teacherManage.getNickName());
                    teacherManageExport.setPhonenumber(teacherManage.getPhonenumber());
                    teacherManageExport.setSex(teacherManage.getSex());
                    teacherManageExports.add(teacherManageExport);
                }
            }
        }

        return teacherManageExports;
    }


    //清洗导入的TeacherManage
    @Override
    public List<TeacherManage>  washTeacherMangerExcel(List<TeacherManage> teacherManages) {
        for (TeacherManage teacherManage : teacherManages) {

            if (!teacherManage.getStrGradeNameList().isEmpty()){
                //所带班级
                List<String> list = Arrays.asList(teacherManage.getStrGradeNameList().split(","));
                List<Long> collect = list.stream().map(Long::parseLong).collect(Collectors.toList());
                teacherManage.setGradeNameList(collect);
            }

            Map<String, List<Long>> mapSubjectWithClass = new HashMap<>();
            //导入的map集合
            String strMapSubject = "{"+teacherManage.getStrMapSubject().replaceAll("=",":")+"}";
            //获取所有的课程中文
            List<String> allSubjectName = iBusSubjectService.getAllSubjectName();
            //科学，数学，语文
            if (!teacherManage.getStrMapSubject().isEmpty()){
                //转为Json对象
                JSONObject jsonObject = JSONObject.parseObject(strMapSubject);
                //String->集合的转换
                for (String subjectName : allSubjectName) {
                    if (strMapSubject.contains(subjectName)){
                        JSONArray jsonArray = jsonObject.getJSONArray(subjectName);
                        List<Object> list = jsonArray.to(List.class);
                        //数据转换存储
                        List<Long> gradeId = new ArrayList<>();
                        //最初的数据为Object  但是我们需要的是Long，所以需要数据转换
                        for (Object o : list) {
                            String s = String.valueOf(o);
                            Long aLong = Long.valueOf(s);
                            gradeId.add(aLong);
                        }
                        //转化数据类型
                        mapSubjectWithClass.put(subjectName,gradeId);
                    }
                }
            }
            teacherManage.setMapSubject(mapSubjectWithClass);

        }
        return teacherManages;
    }




    //纯教师导入，存user表
    @Override
    public boolean addTeacherInfo(TeacherInfoExport teacherInfoExport) {
        boolean save = false;
        //是否重新增加这个教师的身份信息，唯一的冲突就是用户表中是否存在
        LambdaQueryWrapper<TeacherManage> teacherInfoExportLambdaQueryWrapper = new LambdaQueryWrapper<>();
        teacherInfoExportLambdaQueryWrapper.eq(TeacherManage::getNickName,teacherInfoExport.getNickName());
        teacherInfoExportLambdaQueryWrapper.eq(TeacherManage::getPhonenumber,teacherInfoExport.getPhonenumber());
        teacherInfoExportLambdaQueryWrapper.eq(TeacherManage::getSex,teacherInfoExport.getSex());
        TeacherManage teacherCheckManage = this.getOne(teacherInfoExportLambdaQueryWrapper);
        //这个用户为空的话就是做存储
        if (teacherCheckManage == null){
            TeacherManage teacherManage = new TeacherManage();
            //新建用户ID
            Long userId = Long.valueOf(IdWorker.getIdStr().substring(0, 16));
            //userID
            teacherManage.setUserId(userId);
            //手机号
            teacherManage.setPhonenumber(teacherInfoExport.getPhonenumber());
            //密码
            teacherManage.setPassword(SecurityUtils.encryptPassword("123456"));
            //让其手机号作为账号
            teacherManage.setUserName(teacherInfoExport.getPhonenumber());
            //性别
            teacherManage.setSex(teacherInfoExport.getSex());
            //名字
            teacherManage.setNickName(teacherInfoExport.getNickName());
            //部门
            teacherManage.setDeptId(200L);

            //并且判断这个人是不是以教师的身份在userRole表中
            LambdaQueryWrapper<SysUserRole> sysUserRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
            sysUserRoleLambdaQueryWrapper.eq(SysUserRole::getUserId,userId);
            sysUserRoleLambdaQueryWrapper.eq(SysUserRole::getRoleId,101L);
            SysUserRole userRole = iSysUserRoleService.getOne(sysUserRoleLambdaQueryWrapper);
            //如果角色表中没有则添加
            if (userRole == null){
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(userId);
                sysUserRole.setRoleId(101L);
                //加入其任课教师的信息
                iSysUserRoleService.save(sysUserRole);
            }

            save = this.save(teacherManage);
        }
        return save;
    }


    @Override
    public int changeGradeTeacher(GradeTeacherBody gradeTeacher) {
        Long gradeId = gradeTeacher.getGradeId();
        if (gradeId == null){
            return 0;
        }
        int r = 0;
        //先清除班级的所有教师再插入
        Map<String, Long> teachers = gradeTeacher.getTeacher();
        for (String item:teachers.keySet()){
            Long teacherId = teachers.get(item);
            BusGradeTeacher teacher = new BusGradeTeacher();
            teacher.setGradeId(gradeId);
            teacher.setUserId(teacherId);
            teacher.setPostId(teacherMapper.getPostIdByName(item+"老师"));
            teacher.setSubjectId(teacherMapper.getSubjectIdByName(item));
            try {
                r += teacherMapper.setGradeTeacher(teacher);
            }catch (Exception e){
                //教师已存在
                r = teacherMapper.reSetGradeTeacher(teacher);
            }
        }
        return r;
    }

    @Override
    public List<SubjectTeacher> getSubjectTeacher(String subjectName) {
        return teacherMapper.getSubjectTeacher(subjectName);
    }


    //传入一个教师信息的集合，对其任课等信息进行封装
    public List<TeacherManage> auto(List<TeacherManage> list){

        List<TeacherManage> result = new ArrayList<>();
        for (TeacherManage item : list) {
            //班主任flag
//            boolean checkHeadteacher = false;
            //封装课程及班级
            Map<String, List<Long>> mapSubject = new HashMap<>();
            //拿到这个教师的id
            Long userId = item.getUserId();
            //所带的班级接口
            List<BusGrade> gradedList = iBusGradeService.getBusGradedList(userId);
            for (BusGrade busgrade : gradedList) {
                Long gradeId = busgrade.getGradeId();
                item.addGradeName(gradeId);
            }
            if (!gradedList.isEmpty()){
                item.setHeadTeacher("1");

            }else{
                item.setHeadTeacher("0");
            }

            //教师课程
            LambdaQueryWrapper<BusGradeTeacher> gradeTeacherWrapper = new LambdaQueryWrapper<>();
            gradeTeacherWrapper.eq(BusGradeTeacher::getUserId, userId);
            List<BusGradeTeacher> gradeTeachers = ibusGradeTeacherService.list(gradeTeacherWrapper);
            for (BusGradeTeacher gradeTeacher : gradeTeachers) {
                if (gradeTeacher.getSubjectId() !=null){
                    List<Long> gradeNameList = new ArrayList<>();
                    //拿这个老师教的科目以及班级
                    Long subjectId = gradeTeacher.getSubjectId();

                    Long gradeId = gradeTeacher.getGradeId();
                    //查询科目对应中文
                    LambdaQueryWrapper<BusSubject> subjectLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    subjectLambdaQueryWrapper.eq(BusSubject::getSubjectId, subjectId);
                    BusSubject subject = iBusSubjectService.getOne(subjectLambdaQueryWrapper);
                    //拿到这个课程的对应中文名
                    String subjectName = subject.getSubjectName();
                    if (mapSubject.containsKey(subjectName)) {
                        List<Long> gradeIdList = mapSubject.get(subjectName);
                        gradeIdList.add(gradeId);
                        mapSubject.put(subjectName, gradeIdList);
                    } else {
                        gradeNameList.add(gradeId);
                        mapSubject.put(subjectName, gradeNameList);
                    }
                }
            }
            item.setMapSubject(mapSubject);
            result.add(item);
        }
        return result;
    }



    //封装2.1  用来回显的时候时候
    //传入一个教师信息的集合，对其任课等信息进行封装
    public PointOnwTeacherManageInfo echoTest(PointOnwTeacherManageInfo item){

            //拿到这个教师的id
            Long userId = item.getUserId();

            //所带的班级接口，这里是用来封装其作为班主任教学信息的封装
            List<BusGrade> gradedList = iBusGradeService.getBusGradedList(userId);
            //创建一个集合用来存储其作为班主任的班级
            List<Long> bringGrade = new ArrayList<>();
            //如果这个不为空，它既是班主任
            if (!gradedList.isEmpty()){
                //如果有的就可以直接在这里封装其班主任信息
                item.setHeadTeacher("1");
                for (BusGrade busgrade : gradedList) {
                    //封装其所带班级的Id号
                    bringGrade.add(busgrade.getGradeId());
                }
            }else {
                item.setHeadTeacher("0");
            }


            //创建一个集合用来存储教学信息
            List<String> teachingInfo = new ArrayList<>();

            //教师课程
            LambdaQueryWrapper<BusGradeTeacher> gradeTeacherWrapper = new LambdaQueryWrapper<>();
            gradeTeacherWrapper.eq(BusGradeTeacher::getUserId, userId);
            //这个集合中封装的是班级教学信息，拿到这个用户的教学班级信息
            List<BusGradeTeacher> gradeTeachers = ibusGradeTeacherService.list(gradeTeacherWrapper);
            //这里开始历遍封装
            for (BusGradeTeacher gradeTeacher : gradeTeachers) {
//                List<Long> gradeNameList = new ArrayList<>();
                if(gradeTeacher.getSubjectId() !=null){
                    //拿这个老师教的科目以及班级
                    Long subjectId = gradeTeacher.getSubjectId();
                    //拿它所对应的班级Id
                    Long gradeId = gradeTeacher.getGradeId();
                    //查询科目对应中文
                    LambdaQueryWrapper<BusSubject> subjectLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    subjectLambdaQueryWrapper.eq(BusSubject::getSubjectId, subjectId);
                    BusSubject subject = iBusSubjectService.getOne(subjectLambdaQueryWrapper);
                    //拿到这个课程的对应中文名
                    String subjectName = subject.getSubjectName();

                    //现在这里要对课程等进行封装
                    //首先要考虑到班主任班级和任课班级的一个区分
                    // 如果这个班级Id是所带班级里面的，那就证明此时这个时候是他是这个班级
                    String str;
                    if (bringGrade.contains(gradeId)){
                        //拼接为班主任:科目：班级id
                        str = "班主任:" + subjectName + ":" + gradeId;
                    }else {
                        //拼接为班主任:科目：班级id
                        str = "任课老师:" + subjectName + ":" + gradeId;
                    }
                    teachingInfo.add(str);
                }
            }
            //将教学信息集合赋值
            item.setTeachingInfo(teachingInfo);
            return item;
    }


    //获取所有教师的用户ID
    @Override
    public List<Long> getTeacherManageInfo() {
        QueryWrapper<MySysRole> sysRoleQueryWrapper = new QueryWrapper<>();
        sysRoleQueryWrapper.last("WHERE role_key = \"bzr\" OR role_key = \"teacher\"");
        List<MySysRole> mySysRoles = iSysRoleService.list(sysRoleQueryWrapper);
        //存储教师的roleId
        List<Long> roleId = new ArrayList<>();
        for (MySysRole mySysRole : mySysRoles) {
            roleId.add(mySysRole.getRoleId());
        }
        //RoleId所对应的用户Id
        LambdaQueryWrapper<SysUserRole> sysUserRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysUserRoleLambdaQueryWrapper.in(SysUserRole::getRoleId,roleId);
        List<SysUserRole> sysUserRoles = iSysUserRoleService.list(sysUserRoleLambdaQueryWrapper);
        List<Long> teacherIds = new ArrayList<>();
        for (SysUserRole sysUserRole : sysUserRoles) {
            if (!teacherIds.contains(sysUserRole.getUserId())){
                teacherIds.add(sysUserRole.getUserId());
            }
        }
        return teacherIds;
    }



    //导入Excel时需要用到的添加方法，该方法只适用于教师导入的用户添加
    @Override
    public boolean addTeacherManageExcelInfo(TeacherManageExport teacherManageExport) {
        //姓名
        String nickName = teacherManageExport.getNickName();
        //手机号码
        String phoneNumber = teacherManageExport.getPhonenumber();
        //用户性别
        String sex = teacherManageExport.getSex();
        //------用户表--------

        LambdaQueryWrapper<TeacherManage> teacherManageLambdaQueryWrapper = new LambdaQueryWrapper<>();
        teacherManageLambdaQueryWrapper.eq(TeacherManage::getNickName,nickName);
        teacherManageLambdaQueryWrapper.eq(TeacherManage::getPhonenumber,phoneNumber);
        TeacherManage teacherManage = this.getOne(teacherManageLambdaQueryWrapper);
        //用来存储这个用户的Id
        Long userId;
        //用户存在与否
        if (teacherManage == null){
            //如果为null就给它创建一个对象
            teacherManage = new TeacherManage();
            //等于空就存储教师信息
            teacherManage.setNickName(nickName);
            teacherManage.setPhonenumber(phoneNumber);
            teacherManage.setSex(sex);
            //账号即手机号
            teacherManage.setUserName(phoneNumber);
            teacherManage.setPassword(SecurityUtils.encryptPassword("123456"));
            //重写加一条用户信息
             this.save(teacherManage);
            //此时以及加了一条数据，现在要拿到这个人的用户Id，需要回调其信息
            teacherManageLambdaQueryWrapper.eq(TeacherManage::getUserName,phoneNumber);
            userId = this.getOne(teacherManageLambdaQueryWrapper).getUserId();
        }else {
            //如果这个用户存在就拿其Id
            userId = teacherManage.getUserId();
        }

        //并且判断这个人是不是以教师的身份在userRole表中
        LambdaQueryWrapper<SysUserRole> sysUserRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysUserRoleLambdaQueryWrapper.eq(SysUserRole::getUserId,userId);
        sysUserRoleLambdaQueryWrapper.eq(SysUserRole::getRoleId,101L);
        SysUserRole userRole = iSysUserRoleService.getOne(sysUserRoleLambdaQueryWrapper);
        //如果角色表中没有则添加
        if (userRole == null){
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(userId);
            sysUserRole.setRoleId(101L);
            //加入其任课教师的信息
            iSysUserRoleService.save(sysUserRole);
        }

        //---------班主任的判断-------
        //如果班主任所带班级这个字段不是空，则证明他是班主任
        if (!teacherManageExport.getBringClass().trim().isEmpty()){
            //如果是班主任
            //这里就标记其是班主任
            teacherManage.setHeadTeacher("1");
            //如果是班主任，那么可以对这个字段进行切割了
            String[] bringClass = teacherManageExport.getBringClass().split(",");
            for (String aClass : bringClass) {
                Long gradeId = Long.valueOf(aClass);
                LambdaQueryWrapper<BusGrade> busGradeWrapper = new LambdaQueryWrapper<>();
                busGradeWrapper.eq(BusGrade::getGradeId,gradeId);
                BusGrade busGrade = iBusGradeService.getOne(busGradeWrapper);
                busGrade.setUserId(userId);
                //修改其指定班级的班主任的信息
                 iBusGradeService.update(busGrade, busGradeWrapper);
            }

            //并且判断这个人是不是以教师的身份在userRole表中
            LambdaQueryWrapper<SysUserRole> sysUserRoleWrapper = new LambdaQueryWrapper<>();
            sysUserRoleWrapper.eq(SysUserRole::getUserId,userId);
            sysUserRoleWrapper.eq(SysUserRole::getRoleId,100L);
            SysUserRole userRoleHead = iSysUserRoleService.getOne(sysUserRoleWrapper);
            //如果角色表中没有则添加
            if (userRoleHead == null){
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(userId);
                sysUserRole.setRoleId(100L);
                //加入其任课教师的信息
                iSysUserRoleService.save(sysUserRole);
            }
            //并且判断这个人是不是以班主任的身份在userPost表中
            LambdaQueryWrapper<UserPost> sysUserPostWrapper = new LambdaQueryWrapper<>();
            sysUserPostWrapper.eq(UserPost::getUserId,userId);
            sysUserPostWrapper.eq(UserPost::getPostId,1L);
            UserPost userPost = iUserPostService.getOne(sysUserPostWrapper);
            //如果角色表中没有则添加
            if (userPost == null){
                UserPost userPostAdd = new UserPost();
                userPostAdd.setPostId(1L);
                userPostAdd.setUserId(userId);
                //加入其班主任Post的信息
                iUserPostService.save(userPostAdd);
            }
        }
        //这个对象的授课课程名称
        String subjectName = teacherManageExport.getSubjectName();
        //通过课程的名称拿课程Id
        LambdaQueryWrapper<BusSubject> subjectLambdaQueryWrapper = new LambdaQueryWrapper<>();
        subjectLambdaQueryWrapper.eq(BusSubject::getSubjectName,subjectName);
        BusSubject subject = iBusSubjectService.getOne(subjectLambdaQueryWrapper);
        Long subjectId;
        if (subject == null){
            //没有就新增一个课程
            BusSubject busSubject = new BusSubject();
            busSubject.setSubjectName(subjectName);
            iBusSubjectService.addSubject(busSubject);
            //回调课程
            subjectId = iBusSubjectService.getOne(subjectLambdaQueryWrapper).getSubjectId();
        }else {
            subjectId = subject.getSubjectId();
        }

        //对于课程Post中的信息
        LambdaQueryWrapper<UserPost> userPostLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userPostLambdaQueryWrapper.eq(UserPost::getUserId,userId);
        userPostLambdaQueryWrapper.eq(UserPost::getPostId,subjectId+1);
        UserPost userPost = iUserPostService.getOne(userPostLambdaQueryWrapper);
        if (userPost == null){
            UserPost userPostAdd = new UserPost();
            userPostAdd.setPostId(subjectId+1);
            userPostAdd.setUserId(userId);
            //加入其班主任Post的信息
            iUserPostService.save(userPostAdd);
        }

        String[] classes = teacherManageExport.getClasses().split(",");
        //对班级信息的绑定
        boolean flag = false;
        for (String gradeId : classes) {
            BusGradeTeacher busGradeTeacher = new BusGradeTeacher();
            busGradeTeacher.setGradeId(Long.valueOf(gradeId));

            //如果这个班级ID是在所带班级里面-->PostId=1
            if (teacherManageExport.getBringClass().contains(gradeId)){
                BusGradeTeacher busGradeHeadTeacher = new BusGradeTeacher();
                busGradeHeadTeacher.setGradeId(busGradeTeacher.getGradeId());
                busGradeHeadTeacher.setPostId(1L);
                busGradeHeadTeacher.setUserId(userId);

                //为了避免一个人多条数据，先再班级授课信息表中，先查询一遍
                LambdaQueryWrapper<BusGradeTeacher> busGradeHeadWrapper = new LambdaQueryWrapper<>();
                busGradeHeadWrapper.eq(BusGradeTeacher::getGradeId,busGradeHeadTeacher.getGradeId());
                busGradeHeadWrapper.eq(BusGradeTeacher::getPostId,busGradeHeadTeacher.getPostId());
                busGradeHeadWrapper.eq(BusGradeTeacher::getUserId,busGradeHeadTeacher.getUserId());
                busGradeHeadWrapper.eq(BusGradeTeacher::getSubjectId,busGradeHeadTeacher.getSubjectId());
                BusGradeTeacher gradeTeacherInfo = ibusGradeTeacherService.getOne(busGradeHeadWrapper);
                if (gradeTeacherInfo == null){
                    ibusGradeTeacherService.save(busGradeHeadTeacher);
                }
            }

            //PostId = subjectId + 1
            busGradeTeacher.setPostId(subjectId + 1);
            busGradeTeacher.setUserId(userId);
            busGradeTeacher.setSubjectId(subjectId);
            //为了避免一个人多条数据，先再班级授课信息表中，先查询一遍
            LambdaQueryWrapper<BusGradeTeacher> busGradeLambdaQueryWrapper = new LambdaQueryWrapper<>();
            busGradeLambdaQueryWrapper.eq(BusGradeTeacher::getGradeId,busGradeTeacher.getGradeId());
            busGradeLambdaQueryWrapper.eq(BusGradeTeacher::getPostId,busGradeTeacher.getPostId());
            busGradeLambdaQueryWrapper.eq(BusGradeTeacher::getUserId,busGradeTeacher.getUserId());
            busGradeLambdaQueryWrapper.eq(BusGradeTeacher::getSubjectId,busGradeTeacher.getSubjectId());
            BusGradeTeacher gradeTeacherInfo = ibusGradeTeacherService.getOne(busGradeLambdaQueryWrapper);
            if (gradeTeacherInfo == null){
                //存储该条教学信息
                try {
                    flag = ibusGradeTeacherService.save(busGradeTeacher);
                }catch (Exception e){
                    throw new MyException("任课岗位存在冲突"+"("+teacherManageExport.getNickName()+busGradeTeacher.getGradeId()+subjectName+")");
                }
            }
        }
        return flag;
    }



}
